package com.baizhi.config;

import com.baizhi.dao.UserDao;
import com.baizhi.entity.Role;
import com.baizhi.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * ClassName: MyUserDetailService
 * Description:
 * Date: 2022/11/03 PM 9:01
 * <p>
 * project: codes
 * package: com.baizhi.config
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
@Component
public class MyUserDetailServiceImpl implements UserDetailsService {

    private final UserDao userDao;

    @Autowired
    public MyUserDetailServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    /**
     * Locates the user based on the username. In the actual implementation, the search
     * may possibly be case sensitive, or case insensitive depending on how the
     * implementation instance is configured. In this case, the <code>UserDetails</code>
     * object that comes back may have a username that is of a different case than what
     * was actually requested..
     *
     * @param username the username identifying the user whose data is required.
     * @return a fully populated user record (never <code>null</code>)
     * @throws UsernameNotFoundException if the user could not be found or the user has no
     *                                   GrantedAuthority
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.查询用户
        User user = userDao.loadUserByUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new UsernameNotFoundException("用户名不正确~");
        }
        // 2.查询权限信息
        List<Role> roles = userDao.getRolesByUid(user.getId());
        user.setRoles(roles);
        return user;
    }
}
